package com.blueocean_health.care.management.handle;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import com.blueocean_health.care.management.common.base.string.StringUtils;

/**
* @author huyanqiu
* @date 2018年3月21日 下午3:44:55
* @version 版本号：1.0
*/
@SuppressWarnings("rawtypes")
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({List.class})
public class Str2ListHandler extends BaseTypeHandler<List>{

	@Override
	public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return this.getStringList(rs.getString(columnName));
	}
	
	@Override
	public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return this.getStringList(rs.getString(columnIndex));
	}

	@Override
	public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return this.getStringList(cs.getString(columnIndex));
	}
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType)
			throws SQLException {
		 //由于BaseTypeHandler中已经把parameter为null的情况做了处理，所以这里我们就不用再判断parameter是否为空了，直接用就可以了  
	       StringBuffer result = new StringBuffer();  
	       if (!StringUtils.isEmpty(parameter)) {
	    	   for (Object value : parameter) {
	    		   result.append(value).append(",");
	    	   }
	    	   result.deleteCharAt(result.length() - 1);
	    	   ps.setString(i, result.toString());
	       } else {
	    	   ps.setString(i, "");
	       }
	}
	
	private List getStringList(String columnValue) {
		if (columnValue==null || "".equals(columnValue)) {
			return new ArrayList<>();
		}
		String[] split = columnValue.split(",");
		List<Object> list = new ArrayList<>();
		for (int i=0; i<split.length; i++) {
			list.add(split[i]);
		}
		return list;
	}

}
